const pinataSDK = require("@pinata/sdk")
const path = require("path")
const fs = require("fs")
require("dotenv").config()

// @ts-ignore
const pinata = new pinataSDK({
    pinataApiKey: process.env.PINATA_API_KEY || "",
    pinataSecretApiKey: process.env.PINATA_API_SEC_KEY || "",
})

/**
 * pinata提供将自己的文件上传到IPFS的API,虽然不像nft.storage一样是ipfs多节点保存.但是比本地节点好
 *
 * @param imagesFilesPath NFT文件路径
 */
async function storeImages(imagesFilesPath) {
    const fullImagePath = path.resolve(imagesFilesPath)
    //读取目录文件名返回文件名数组
    const imageFile = fs.readdirSync(fullImagePath)

    let responses = []
    for (const fileIndex in imageFile) {
        console.log(`uploading  ${imageFile[fileIndex]} to pinata ipfs node`)

        const options = {
            pinataMetadata: {
                name: imageFile[fileIndex],
            },
            pinataOptions: {
                cidVersion: 0,
            },
        }
        try {
            const imageFileStream = fs.createReadStream(
                `${fullImagePath}/${imageFile[fileIndex]}`
            )
            //pinFileToIPFS方法返回上传文件的CID
            const response = await pinata.pinFileToIPFS(
                imageFileStream,
                options
            )
            responses.push(response)
        } catch (err) {
            console.warn(err)
        }
    }
    console.log("done")
    //console.log(responses)
    return { responses, imageFile }
}
/**
 *
 * @param  metaData 对NFT的描述数据(jsonMetaData)
 * @returns 上传到pinata的tokenuri
 */
async function storeTokenUriMetadata(metaData) {
    try {
        const options = {
            pinataMetadata: {
                name: metaData.name,
            },
            pinataOptions: {
                cidVersion: 0,
            },
        }

        return await pinata.pinJSONToIPFS(metaData, options)
    } catch (err) {
        console.warn(err)
    }
    return null
}
module.exports = { storeImages, storeTokenUriMetadata }
